package org.jeecg.modules.demo.hdPeerSupervisionLeader3.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.modules.demo.hdLeader.mapper.HdLeaderMapper;
import org.jeecg.modules.demo.hdPeerSupervisionLeader3.entity.HdPeerSupervisionLeader3;
import org.jeecg.modules.demo.hdPeerSupervisionLeader3.mapper.HdPeerSupervisionLeader3Mapper;
import org.jeecg.modules.demo.hdPeerSupervisionLeader3.service.IHdPeerSupervisionLeader3Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * @Description: 同级监督(领导人魏)
 * @Author: jeecg-boot
 * @Date:   2025-07-22
 * @Version: V1.0
 */
@Service
public class HdPeerSupervisionLeader3ServiceImpl extends ServiceImpl<HdPeerSupervisionLeader3Mapper, HdPeerSupervisionLeader3> implements IHdPeerSupervisionLeader3Service {
    @Autowired
    private HdLeaderMapper hdLeaderMapper;
    @Override
    public byte[] generateExcelBytes(List<HdPeerSupervisionLeader3> exportList) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("导出记录");

            // 设置默认行高和列宽
            sheet.setDefaultRowHeightInPoints(20); // 设置默认行高
            sheet.setDefaultColumnWidth(15); // 设置默认列宽

            // 创建样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            CellStyle dataStyle = createDataStyle(workbook);

            Row titleRow = sheet.createRow(0);
            titleRow.setHeightInPoints(45); // 标题行高
            CellRangeAddress titleMerge = new CellRangeAddress(0, 0, 0, 5); // 合并0-5列（共5列）
            sheet.addMergedRegion(titleMerge);
            Cell titleCell = titleRow.createCell(0);
            String leader = exportList.get(0).getLeader();
            String exportName=hdLeaderMapper.queryAllByLeader(leader);
            titleCell.setCellValue(leader+exportName);
//            titleCell.setCellValue("江西公司党委委员、总会计师魏成伟履行全面从严治党“一岗双责”情况表");


            // 标题样式
            CellStyle titleStyle = workbook.createCellStyle();
            Font titleFont = workbook.createFont();
            titleFont.setBold(true);
            titleFont.setFontHeightInPoints((short) 16); // 字体大小
            titleStyle.setFont(titleFont);
            titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中

//            // 设置背景色
//            titleStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//            titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//            // 设置边框
//            titleStyle.setBorderTop(BorderStyle.THIN);
//            titleStyle.setBorderBottom(BorderStyle.THIN);
//            titleStyle.setBorderLeft(BorderStyle.THIN);
//            titleStyle.setBorderRight(BorderStyle.THIN);
            titleCell.setCellStyle(titleStyle);
            // 创建表头行
            Row headerRow = sheet.createRow(1);
            headerRow.setHeightInPoints(25); // 设置表头行高


            String[] headers = {"工作项目", "工作内容", "记录部门","工作开展情况","工作开展情况","频次"};
            // 设置列宽（与表头数组对应）
            sheet.setColumnWidth(0, 15 * 256); // 工作项目
            sheet.setColumnWidth(1, 40 * 256); // 工作内容
            sheet.setColumnWidth(2, 15 * 256); // 记录部门
            sheet.setColumnWidth(3, 45 * 256); // 工作开展情况
            sheet.setColumnWidth(4, 45 * 256);// 工作开展评价
            sheet.setColumnWidth(5, 15 * 256); // 频次
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据行
            int rowNum = 2;
            for (HdPeerSupervisionLeader3 hdPeerSupervisionLeader: exportList) {
                Row row = sheet.createRow(rowNum++);
                setCellValue(row, 0, hdPeerSupervisionLeader.getProject(), dataStyle);
                setCellValue(row, 1, hdPeerSupervisionLeader.getWorkContent(), dataStyle);
                setCellValue(row, 2, hdPeerSupervisionLeader.getCompanyDepartment(), dataStyle);
                setCellValue(row, 3, hdPeerSupervisionLeader.getWorkProgress(), dataStyle);
                setCellValue(row, 4, hdPeerSupervisionLeader.getImplementationEvaluation(), dataStyle);
                setCellValue(row, 5, hdPeerSupervisionLeader.getFrequency(), dataStyle);
            }


            // 合并相同列的连续相同单元格
            // 根据表头数组索引合并对应的列

            // 对每个列应用合并逻辑
            mergeSameCells(sheet, 0);
            mergeSameCells(sheet, 1);


//            // 智能列宽调整（新增的核心优化）
//            for (int i = 0; i < headers.length; i++) {
//                sheet.autoSizeColumn(i);
//                int currentWidth = sheet.getColumnWidth(i);
//
//                // 动态计算新宽度（中文适配）
//                int newWidth = Math.min(Math.max(
//                        (int)(currentWidth * 1.2) + 512, // 增加20%宽度+额外缓冲
//                        10 * 256                         // 最小宽度10字符
//                ), 100 * 256);                       // 最大宽度限制100字符
//
//                sheet.setColumnWidth(i, newWidth);
//            }

            // 将Excel写入字节数组（关键修改）
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            return baos.toByteArray(); // 返回字节数组
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    // 创建优化的表头样式
    static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 设置背景色
        style.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置边框
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 设置字体
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        font.setFontName("宋体"); // 使用宋体显示中文
        style.setFont(font);

        // 居中对齐
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 自动换行
        style.setWrapText(true);

        return style;
    }

    // 创建数据行样式
    static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 设置边框
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 设置自动换行
        style.setWrapText(true);

        // 垂直居中
        style.setVerticalAlignment(VerticalAlignment.TOP); // 顶部对齐更美观

        return style;
    }

    static void setCellValue(Row row, int columnIndex, String value, CellStyle style) {
        if (row == null) return;

        Cell cell = row.createCell(columnIndex);
        cell.setCellValue(value != null ? value : ""); // 防止null值

        // 创建新的样式，确保居中对齐
        CellStyle newStyle = row.getSheet().getWorkbook().createCellStyle();
        if (style != null) {
            newStyle.cloneStyleFrom(style);
        }

        // 设置水平和垂直居中
        newStyle.setAlignment(HorizontalAlignment.CENTER);
        newStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        cell.setCellStyle(newStyle);

        // 特别处理长文本内容，自动调整行高
        if (value != null && value.length() > 0) {
            row.setHeightInPoints(calculateRowHeight(value));
        }
    }

    // 计算行高（根据文本长度）
    private static float calculateRowHeight(String text) {
        int lineCount = (int) Math.ceil(text.length() / 20.0); // 每80字符为一行
        return Math.max(100, 15 * lineCount); // 最小行高50，每行增加15
    }

    // 合并相同列的连续相同单元格
    static void mergeSameCells(Sheet sheet, int columnIndex) {
        int startRow = 2; // 数据从第3行开始（索引2）
        int lastRow = sheet.getLastRowNum();

        if (lastRow <= startRow) return;

        for (int i = startRow + 1; i <= lastRow; i++) {
            Row currentRow = sheet.getRow(i);
            Row previousRow = sheet.getRow(i - 1);

            if (currentRow == null || previousRow == null) continue;

            Cell currentCell = currentRow.getCell(columnIndex);
            Cell previousCell = previousRow.getCell(columnIndex);

            String currentValue = getCellValueAsString(currentCell);
            String previousValue = getCellValueAsString(previousCell);

            if (!currentValue.equals(previousValue)) {
                if (i - 1 > startRow) {
                    sheet.addMergedRegion(new CellRangeAddress(startRow, i - 1, columnIndex, columnIndex));

                    // 合并后居中显示
                    centerMergedCells(sheet, startRow, i - 1, columnIndex);
                }
                startRow = i;
            } else if (i == lastRow) {
                sheet.addMergedRegion(new CellRangeAddress(startRow, i, columnIndex, columnIndex));

                // 合并后居中显示
                centerMergedCells(sheet, startRow, i, columnIndex);
            }
        }
    }

    // 获取单元格值
    private static String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }

    // 合并后单元格垂直居中
    private static void centerMergedCells(Sheet sheet, int firstRow, int lastRow, int column) {
        Row firstRowObj = sheet.getRow(firstRow);
        if (firstRowObj == null) return;

        Cell firstCellObj = firstRowObj.getCell(column);
        if (firstCellObj == null) return;

        CellStyle originalStyle = firstCellObj.getCellStyle();
        CellStyle style = sheet.getWorkbook().createCellStyle();
        style.cloneStyleFrom(originalStyle);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        for (int i = firstRow; i <= lastRow; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                Cell cell = row.getCell(column);
                if (cell != null) {
                    cell.setCellStyle(style);
                }
            }
        }
    }
}
